package com.wwx.exception;

import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * ConstraintViolationHandler
 *
 * @author 王伟欣
 * @version V1.0
 * @email w17731138318@126.com
 * @creator 2023-02-11 11:40
 * @company 晶品科技
 * @copyright 晶品科技 · 石家庄 · 技术二部
 */
@ControllerAdvice
public class ConstraintViolationHandler {

	private static ResourceBundleMessageSource getMessageSource() {
		ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource();
		bundleMessageSource.setDefaultEncoding("UTF-8");
		bundleMessageSource.setBasenames("i18n/validation", "i18n/validation_common");
		return bundleMessageSource;
	}
	/**
	 * 捕获方法参数校验异常
	 */
	@ExceptionHandler(ConstraintViolationException.class)
	@ResponseBody
	public ResponseEntity<HashMap<String,Object>> constraintViolationExceptionHandler(ConstraintViolationException e){
		Set<ConstraintViolation<?>> message = e.getConstraintViolations();
		HashMap<String,Object> map = new HashMap<>();
		message.forEach(msg ->{
			String path = msg.getPropertyPath().toString();
			String field = path.substring(path.indexOf(".")+1);
			map.put(field,msg.getMessageTemplate());
		});
		return ResponseEntity.ok(map);
	}

	/**
	 * 捕获实体参数校验异常
	 */
	@ExceptionHandler(MethodArgumentNotValidException.class)
	@ResponseBody
	public ResponseEntity<HashMap<String,Object>> resolveMethodArgumentNotValidException(MethodArgumentNotValidException e){
		List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
		HashMap<String,Object> map = new HashMap<>();
		allErrors.forEach(error -> {
			FieldError fieldError = (FieldError) error;
			map.put(fieldError.getField(),fieldError.getDefaultMessage());
		});
		return ResponseEntity.ok(map);
	}
}
